package com.clp.inflxudb.core;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

class FluxContextImpl implements FluxContext{
    private EnumSet<FluxLib> fluxLibs;
    private Map<String, Flux> fluxMap;

    public FluxContextImpl() {
        this.fluxLibs = EnumSet.noneOf(FluxLib.class);
        this.fluxMap = new HashMap<>();
    }

    private void checkNotNull(Object obj) {
        if (obj == null) throw new NullPointerException();
    }

    @Override
    public FluxContext importLib(FluxLib lib) {
        checkNotNull(lib);
        fluxLibs.add(lib);
        return this;
    }

    @Override
    public FluxContext importLibs(FluxLib... libs) {
        for (FluxLib lib : libs) {
            checkNotNull(lib);
            fluxLibs.add(lib);
        }
        return this;
    }

    @Override
    public FluxContext putFlux(String fluxName, Flux flux) {
        checkNotNull(fluxName);
        checkNotNull(flux);
        fluxMap.put(fluxName, flux);
        return this;
    }

    @Override
    public FluxContext removeFlux(String fluxName) {
        fluxMap.remove(fluxName);
        return this;
    }

    @Override
    public String yield(String fluxName) {
        return yield(fluxName, "");
    }

    @Override
    public String yield(String fluxName, String yieldName) {
        checkNotNull(fluxName);
        StringBuilder sb = new StringBuilder();
        // 先导库
        fluxLibs.forEach(lib -> sb.append(lib.getFluxStr()).append("\n"));
        // 再导Flux语句
        fluxMap.forEach((fName, flux) -> sb.append("\n").append(fName).append(" = ").append(flux.toString()));
        // 最后提交给定的语句
        sb.append("\n\n").append(fluxName).append(" |> yield(" + yieldName + ")");
        return sb.toString();
    }
}
